<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单退换货类
 * @package  module/base/bill
 * @author   allen.qiang
 * @version 1.0
 */
quanli_require('module/base/promotion/quanliCoupon.class.php');
quanli_require('module/base/promotion/quanliCard.class.php');
quanli_require('module/func/eai.func.php');

class billReturn {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询退货/拒收主表信息
     * @param array $arg_array                          查询参数数组
     * @return null|array
     */
    public function searchBillReturn (&$arg_array) {

        //sql字符串
        $sql = '';
        $sql_count = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND b.bill_no = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['bill_no']);
        }

        //订单编号
        if (isset($arg_array['bill_code']) && is_numeric($arg_array['bill_code'])) {
            $sql .= ' AND b.bill_code LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['bill_code']);
        }

        //退款单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND b.return_no = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['return_no']);
        }

        //退款单编号
        if (isset($arg_array['return_code']) && !empty($arg_array['return_code'])) {
            $sql .= ' AND b.return_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['return_code']);
        }

        //会员名
        if (isset($arg_array['custID']) && !empty($arg_array['custID']) ) {
            $sql .= ' AND b.custID LIKE ?';
            $params_type .= 's';
            $params_array[] = "%".trim($arg_array['custID'])."%";
        }

        //配送站
        if (isset($arg_array['distribution_id']) && !empty($arg_array['distribution_id']) ) {
            $sql .= ' AND b.distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['distribution_id']);
        }

        //拒收/退货原因
        if (isset($arg_array['return_reason_id_1']) && is_numeric($arg_array['return_reason_id_1'])) {
            $sql .= ' AND b.return_reason_id_1 = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_reason_id_1'];
        }
        if (isset($arg_array['return_reason_id_2']) && is_numeric($arg_array['return_reason_id_2'])) {
            $sql .= ' AND b.return_reason_id_2 = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_reason_id_2'];
        }

        //拒收还是退货
        if (isset($arg_array['service_type']) && in_array($arg_array['service_type'], array(1, 2 ,3)) ) {
            $sql .= ' AND b.return_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_type'];
        }

        //状态
        if (isset($arg_array['return_status']) && in_array($arg_array['return_status'], array(1, 2, 3, 4 ,5)) ) {
            $sql .= ' AND b.return_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_status'];
        }
        //add by allen.qiang 20141023 退货单增加“配送日期”作为查询条件--start
        //配送日期
        if (isset($arg_array['sendDate']) && !empty($arg_array['sendDate']) ){
            $sql .= ' AND (SELECT COUNT(*) FROM bill_master WHERE bill_code =b.`bill_code` AND send_date=?) >0';
            $params_type .= 's';
            $params_array[] = $arg_array['sendDate'];
        }
        //add by allen.qiang 20141023 退货单增加“配送日期”作为查询条件--end

        //创建开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
            $sql .= ' AND b.createTime > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }

        //创建结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND b.createTime < ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        //审核开始时间
        if (isset($arg_array['auditStartDate']) && !empty($arg_array['auditStartDate']) ){
            $sql .= ' AND b.confirm_time > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['auditStartDate'] . ' 00:00:00';
        }

        //审核结束时间
        if (isset($arg_array['auditEndDate']) && !empty($arg_array['auditEndDate']) ){
            $sql .= ' AND b.confirm_time < ?';
            $params_type .= 's';
            $params_array[] = $arg_array['auditEndDate'] . ' 23:59:59';
        }

        if (isset($arg_array['return_memo']) && !empty($arg_array['return_memo'])) {
            $sql .= ' AND b.return_memo LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['return_memo'] . '%';
        }
        $sql_count=$sql;
        //订单平台
        if(isset($arg_array['billPlatform']) && is_numeric($arg_array['billPlatform'])){
            //mod by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---start
                //$sql .= ' AND a.billPlatform = ?';
            $sql .= ' AND b.billPlatform = ?';
            $sql_count .= ' AND a.billPlatform = ?';
            //mod by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---end
            $params_type .= 'i';
            $params_array[] = $arg_array['billPlatform'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
            $sql_count .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
            $sql_count =  ' WHERE ' . substr($sql_count, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_return b INNER JOIN bill_master a ON a.bill_code = b.bill_code' . $sql_count;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            //add by allen.qiang 20141024 退货单增加“配送日期”作为查询条件--start
            //$search_sql = 'SELECT * FROM bill_return ' . $sql;
          /*  $search_sql = "SELECT (SELECT CASE  WHEN send_end_time='00:00:00' THEN
                      CONCAT_WS('', send_date, ' ', send_start_time) ELSE
                      CONCAT_WS('', send_date,' ', send_start_time,'～', send_end_time) END
                      FROM bill_master WHERE bill_code =b.`bill_code`) AS send_Date1,
                      (SELECT send_date FROM bill_master WHERE bill_code =b.`bill_code`) AS send_date,
                      b.*,a.billPlatform  FROM bill_return b INNER JOIN bill_master a ON b.bill_code = a.bill_code " . $sql;*/
            //add by allen.qiang 20141024 退货单增加“配送日期”作为查询条件--end
//            error_log(print_r($search_sql,1));

            //add by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---start
            $search_sql="SELECT * FROM (
                      SELECT v.*,GROUP_CONCAT(`bill_return_goods`.`goods_name` SEPARATOR ',' )AS goods_name FROM (
                      SELECT (SELECT CASE  WHEN send_end_time='00:00:00' THEN
                      CONCAT_WS('', send_date, ' ', send_start_time) ELSE
                      CONCAT_WS('', send_date,' ', send_start_time,'～', send_end_time) END
                      FROM bill_master WHERE bill_code =b.`bill_code`) AS send_Date1,
                      (SELECT send_date FROM bill_master WHERE bill_code =b.`bill_code`) AS send_date,
                      b.*,a.billPlatform  FROM bill_return b INNER JOIN bill_master a ON b.bill_code = a.bill_code) v
                      LEFT JOIN bill_return_goods ON v.`return_no`=bill_return_goods.`return_no` GROUP BY v.`return_no`) b". $sql;
            //add by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---end

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {

                if ($item->return_status == 1) {
                    $item->return_status_name = '未审核';
                } else if ($item->return_status == 2) {
                    $item->return_status_name = '已审核';
                } else if ($item->return_status == 3) {
                    $item->return_status_name = '已收货';
                } else if ($item->return_status == 4) {
                    $item->return_status_name = '已取消';
                }
                //add by allen.qiang 20141110 FUN-BK-0022-配送部自购业务需求 --start
                else if ($item->return_status == 5) {
                    $item->return_status_name = '已配送自购';
                }
                //add by allen.qiang 20141110 FUN-BK-0022-配送部自购业务需求 --end


                $item_array[] = array(
                    'createTime' => $item->createTime,
                    'return_no' => $item->return_no,
                    'return_code' => $item->return_code,
                    'bill_no' => $item->bill_no,
                    'bill_code' => $item->bill_code,
                    //add by allen.qiang 20141024 退货单增加“配送日期”作为查询条件--start
                    'send_Date' =>$item->send_Date1,
                    //add by allen.qiang 20141024 退货单增加“配送日期”作为查询条件--end
                    'pcustID' => $item->pcustID,
                    'custID' => $item->custID,
                    'creator' => $item->creator,
                    'confirmor' => $item->confirmor,
                    'confirm_time' => $item->confirm_time,
                    'return_price' => $item->return_price,
                    'return_amount' => $item->return_amount,
                    'custName' => decryptD($item->deliver_name),
                    'mobile' => decryptD($item->deliver_mobile),
                    'service_type' => $item->service_type,
                    'service_type_name' => $item->return_type == 1 ? '退货' : '换货',
                    'province' => $item->province,
                    'city' => $item->city,
                    'county' => $item->county,
                    'address' => decryptD($item->deliver_address),
                    'goods_return_type' => $item->goods_return_type,
                    'goods_return_type_name' => $item->goods_return_type == 1 ? '快递至商家' : '上门取件',
                    'pick_province' => $item->deliver_province,
                    'pick_city' => $item->deliver_city,
                    'pick_county' => $item->deliver_county,
                    'pick_address' => decryptD($item->pick_address),
                    'return_reason_id_1' => $item->return_reason_id_1,
                    'return_reason_1' => $item->return_reason_1,
                    'return_reason_id_2' => $item->return_reason_id_2,
                    'return_reason_2' => $item->return_reason_2,
                    'return_memo' => $item->return_memo,
                    'return_status' => $item->return_status,
                    'return_status_name' => $item->return_status_name,
                    'confirm_time' => $item->confirm_time,
                    'confirmor' => $item->confirmor,
                    'cancel_time' => $item->cancel_time,
                    'cancel_operator' => $item->cancel_operator,
                    'delivery_time' => $item->delivery_time,
                    'delivery_operator' => $item->delivery_operator,
                    'distribution_id' => $item->distribution_id,
                    'distribution_name' => $item->distribution_name,
                    'billPlatform' => $item->billPlatform,
                    //add by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---start
                    'goods_name' => $item->goods_name,
                    //add by allen.qiang 20141127 FUN-BK-0039-退货单查询界面增加“退货商品”字段列 ---end
                    //add by allen.qiang 20141110 FUN-BK-0022-配送部自购业务需求 --start
                    'purchase_price' => $item->purchase_price,
                    'purchase_operator' => $item->purchase_operator,
                    'purchase_time' => $item->purchase_time,
                    //add by allen.qiang 20141110 FUN-BK-0022-配送部自购业务需求 --end

                    //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
                    'qcviews_time' => $item->qcviews_time,
                    'qcviews_dept' => $item->qcviews_dept,
                    'qcviews_remark' => $item->qcviews_remark
                    //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询退货商品信息
     * @param array $arg_array  查询参数数组
     * @return null|array
     */
    public function searchBillReturnGoods( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_no'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_return_goods ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'return_no' => $item->return_no,
                    'bill_goods_no' => $item->bill_goods_no,
                    'goodsID' => $item->goods_goodsID,
                    'postID' => $item->goods_postID,
                    'product_code' => $item->product_code,
                    'goodsName' => $item->goods_name,
                    'spec' => $item->goods_spec,
                    'goods_amount' => $item->goods_amount
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询退货支付信息
     * @param array $arg_array  查询参数数组
     * @return null|array
     */
    public function searchBillReturnPay( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_no'];
        }

        //订单号
        if (isset($arg_array['payTypeID']) && !empty($arg_array['payTypeID'])) {
            $sql .= ' AND payTypeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['payTypeID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_return_pay ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'return_no' => $item->return_no,
                    'payTypeID' => $item->payTypeID,
                    'payTypeName' => $item->payTypeName,
                    'return_pay' => $item->return_pay,
                    'timeStamp' => $item->timeStamp,
                    'creator' => $item->creator,
                    'createTime' => $item->createTime
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询换货商品信息
     * @param array $arg_array  查询参数数组
     * @return null|array
     */
    public function searchBillExchangeGoods( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_no'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_exchange_goods ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'return_no' => $item->return_no,
                    'postID' => $item->postID,
                    'goodsID' => $item->goodsID,
                    'product_code' => $item->product_code,
                    'goodsName' => $item->goodsName,
                    'spec' => $item->spec,
                    'goods_amount' => $item->goods_amount
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 订单售后服务单
     * @param array $arg_array 参数数组
     * @return array
     */
    public function returnBill( $arg_array ) {

        //加载类文件
        quanli_include('module/base/goods/quanliGoods.class.php');
        quanli_include('module/base/customer/logHandler.class.php');
        quanli_include('module/base/common/quanliCommon.class.php');
        quanli_include('module/base/system/itemHandler.class.php');

        //实例公共类
        $commHandler = new commHandler( $this->dbca );

        //实例字典类
        $itemHandler = new itemHandler($this->dbca);

        //实例日志类
        $logHandler = new logHandler( $this->dbca );

        //实例商品类
        $quanliGoods = new quanliGoods( $this->dbca );

        if (!isset($arg_array['bill_no'], $arg_array['operator'], $arg_array['datetime'], $arg_array['service_type'], $arg_array['return_reason_id_1'],
                   $arg_array['return_reason_id_2'], $arg_array['return_memo'], $arg_array['goods_return_type'], $arg_array['custName'],
                   $arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        if (empty($arg_array['bill_no'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        if (!in_array($arg_array['service_type'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择服务类型');
        }

        if (empty($arg_array['return_reason_id_1'])) {
            return array( 'code' => 400, 'message' => '请选择退换货原因');
        }

        if (!in_array($arg_array['goods_return_type'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择商品返回方式');
        }

        if ($arg_array['goods_return_type'] == 2) {
            if (!isset($arg_array['pick_provinceid'], $arg_array['pick_cityid'], $arg_array['pick_countyid'], $arg_array['pick_address'])
                || empty($arg_array['pick_provinceid']) || empty($arg_array['pick_cityid']) || empty($arg_array['pick_countyid']) || empty($arg_array['pick_address'])) {
                return array( 'code' => 400, 'message' => '请完善取货地址');
            }
        }

        if (empty($arg_array['custName'])) {
            return array( 'code' => 400, 'message' => '联系人姓名不能为空');
        }

        if (!$commHandler->isMobile($arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码输入错误');
        }

        if(isset($arg_array['return_pay']) && !empty($arg_array['return_pay'])){
            foreach($arg_array['return_pay'] as $pay){
                if (!$commHandler->isMoney($pay)) {
                    return array( 'code' => 400, 'message' => '退货金额输入错误');
                }
            }
        }

        if (!isset($arg_array['withdrawAmount'])) {
            return array( 'code' => 400, 'message' => '请选择退货商品' );
        }

        if ($arg_array['service_type'] == 2) {
            if (!isset($arg_array['changeGoods'])) {
                return array( 'code' => 400, 'message' => '请添加换货商品' );
            }
        }

        $return_amount = 0; //退货商品数量
        $return_price = 0; //退货商品总金额
        $return_pay = 0; //退货商品金额
        $return_points = 0; //退货商品返还积分
        $deduct_points = 0; //退货商品扣除积分
        $bill_no = $_REQUEST['bill_no'];
        $bill_goods_array = array(); //订单商品数组
        $bill_return_goods_array = array(); //退货商品数组



        try {

            //查询订单信息
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;
            if (!$this->dbca->fetch($bill_master))
                throw new Exception('订单信息没有找到', 404);
            if ($bill_master->bill_status == 10)
                throw new Exception('订单已取消', 404);
            if (in_array($bill_master->bill_status, array(0, 1, 2, 3 )))
                throw new Exception('订单未开始配送', 404);

            if($bill_master->bill_status != 7 && isset($arg_array['return_pay']) && !empty($arg_array['return_pay'])){//主支付方式类型：1、货到付款 2、在线支付 未完成
                //计算退货金额
                foreach($arg_array['return_pay'] as $key => $pey_money){
                    if( $pey_money != "" ){
                        $return_pay += $pey_money;
                    }
                }
            }

            //查询退货原因
            $sys_item_multilevel = new entity('sys_item_multilevel');
            $sys_item_multilevel->item_id = $arg_array['return_reason_id_1'];
            if (!$this->dbca->fetch($sys_item_multilevel))
                throw new Exception('退货原因1信息没找到', 404);
            $return_reason_1 = $sys_item_multilevel->item_name;

            if (!empty($arg_array['return_reason_id_2'])) {
                $item_multilevel = new entity('sys_item_multilevel');
                $item_multilevel->item_id = $arg_array['return_reason_id_2'];
                if (!$this->dbca->fetch($item_multilevel))
                    throw new Exception('退货原因2信息没找到', 404);
                $return_reason_2 = $item_multilevel->item_name;
            } else {
                $return_reason_id_2 = null;
                $return_reason_2 = null;
            }

            //检查取货地址
            if ($arg_array['goods_return_type'] == 2) {

                //检查地区
                $pick_province = new entity('sys_region');
                $pick_province->id = $arg_array['pick_provinceid'];
                $pick_province->region_level = 1;
                if (!$this->dbca->fetch($pick_province)) {
                    throw new Exception('取货省份不存在', 404);
                }

                $pick_city = new entity('sys_region');
                $pick_city->id = $arg_array['pick_cityid'];
                $pick_city->region_level = 2;
                if (!$this->dbca->fetch($pick_city)) {
                    throw new Exception('取货市区不存在', 404);
                }

                $pick_county = new entity('sys_region');
                $pick_county->id = $arg_array['pick_countyid'];
                $pick_county->region_level = 3;
                if (!$this->dbca->fetch($pick_county)) {
                    throw new Exception('取货地区不存在', 404);
                }

            }

            foreach ($arg_array['withdrawAmount'] as $bill_goods_no => &$withdrawAmount) {

                if (!isset($bill_goods_no, $withdrawAmount) || !is_numeric($bill_goods_no) || !is_numeric($withdrawAmount))
                    throw new Exception( '退货商品信息错误', 404);
                if ($withdrawAmount == 0)
                    continue;

                //查询订单商品信息
                $bill_goods = new entity('bill_goods');
                $bill_goods->bill_no = $bill_no;
                $bill_goods->bill_goods_no = $bill_goods_no;
                if (!$this->dbca->fetch($bill_goods))
                    throw new Exception(sprintf('订单商品「%s」，商品没有找到', $bill_goods->goods_name), 404);
                if ($bill_goods->goods_amount - $bill_goods->goods_withdrawAmount - $bill_goods->goods_rejectionAmount < $withdrawAmount)
                    throw new Exception(sprintf('订单商品「%s」，退货数量大于可货数量', $bill_goods->goods_name), 404);
                $bill_goods->goods_withdrawAmount += $withdrawAmount;
                $bill_goods_array[] = $bill_goods;

                $return_amount += $withdrawAmount;
                $return_price += $bill_goods->goods_purchasePrice * $withdrawAmount;
                $return_points += $bill_goods->goods_pointsPrice * $withdrawAmount;
                $deduct_points += $bill_goods->goods_points * $withdrawAmount;

                //生成退货商品数组
                $bill_return_goods = new entity('bill_return_goods');
                $bill_return_goods->creator = $arg_array['operator'];
                $bill_return_goods->bill_goods_no = $bill_goods->bill_goods_no;
                $bill_return_goods->goods_postID = $bill_goods->goods_postID;
                $bill_return_goods->goods_goodsID = $bill_goods->goods_goodsID;
                $bill_return_goods->goods_name = $bill_goods->goods_name;
                $bill_return_goods->goods_spec = $bill_goods->goods_spec;
                $bill_return_goods->goods_amount = $withdrawAmount;
                $bill_return_goods_array[] = $bill_return_goods;

                //记录订单商品修改日志
                $bill_goods_alter_array[] = '<span class="red">退货商品</span>：' . $bill_goods->goods_name;
                $bill_goods_alter_array[] = '　　规格：' . $bill_goods->goods_spec;
                $bill_goods_alter_array[] = '　　数量：' . $withdrawAmount;
                $bill_goods_alter_array[] = '　　单价：' . $bill_goods->goods_purchasePrice;
                $bill_goods_alter_array[] = '优惠金额：' . round($bill_goods->goods_storePrice - $bill_goods->goods_purchasePrice, 2);
                $bill_goods_alter_array[] = '　总金额：' . round($withdrawAmount * $bill_goods->goods_purchasePrice, 2);

            }

            if($return_amount <= 0){
                throw new Exception('请选择退货商品' , 404);
            }

            //添加订单总订单退货数量
            $bill_master->bill_withdrawAmount += $return_amount;

            //生成退货单信息
            $bill_return_master = new entity('bill_return');
            $bill_return_master->creator = $arg_array['operator'];
            $bill_return_master->bill_no = $bill_no;
            $bill_return_master->bill_code = $arg_array['bill_code'];
            $bill_return_master->return_amount = $return_amount;
            $bill_return_master->custID = $bill_master->custID;
            $bill_return_master->pcustID = $bill_master->pcustID;
            if($bill_master->bill_status != 7){
                $bill_return_master->return_price = $return_pay;
            }else{
                $bill_return_master->return_price = $return_price;
            }
            $bill_return_master->return_points = $return_points;
            $bill_return_master->deduct_points = $deduct_points;
            $bill_return_master->deliver_name = encryptD($arg_array['custName']);
            $bill_return_master->deliver_mobile = encryptD($arg_array['mobile']);
            $bill_return_master->return_type = $arg_array['service_type'];
            $bill_return_master->goods_return_type = $arg_array['goods_return_type'];
            if ($arg_array['goods_return_type'] == 2) {
                $bill_return_master->deliver_province = $pick_province->name;
                $bill_return_master->deliver_city = $pick_city->name;
                $bill_return_master->deliver_county = $pick_county->name;
                $bill_return_master->deliver_address = encryptD($arg_array['pick_address']);
            }
            $bill_return_master->return_reason_id_1 = $arg_array['return_reason_id_1'];
            $bill_return_master->return_reason_1 = $return_reason_1;
            $bill_return_master->return_reason_id_2 = $arg_array['return_reason_id_2'];
            $bill_return_master->return_reason_2 = $return_reason_2;
            $bill_return_master->return_memo = $arg_array['return_memo'];
            $bill_return_master->distribution_id = $bill_master->distribution_id;
            $bill_return_master->distribution_name = $bill_master->distribution_name;
            $bill_return_master->return_status = 1;

            $bill_alter_array[] = '退货数量：' . $return_amount;


        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //保存订单商品信息
            foreach($bill_goods_array as &$bill_goods_obj) {
                $this->dbca->save($bill_goods_obj);
            }

            //保存退货单主表信息
            //mod by allen.qinag 20150420 取seqno优化 start
            //$bill_return_master->return_no = $commHandler->generate_seqno('seqno_return');
            $bill_return_master->return_no = generate_seqno('seqno_return');
            //mod by allen.qinag 20150420 取seqno优化 end
            $this->dbca->save($bill_return_master);

            //保存退货支付方式金额信息
            if(isset($arg_array['return_pay']) && !empty($arg_array['return_pay'])){
                foreach($arg_array['return_pay'] as $key => $pey_money){
                    if( $pey_money != "" ){
                        $bill_pay_return = new entity('bill_return_pay');
                        $bill_pay_return->return_no = $bill_return_master->return_no;
                        $bill_pay_return ->creator = $arg_array['operator'];
                        $bill_pay_return -> payTypeID = $arg_array['payTypeID'][$key];
                        $bill_pay_return -> payTypeName = $arg_array['payTypeName'][$key];
                        $bill_pay_return -> return_pay = $pey_money;
                        $this->dbca->save($bill_pay_return);
                    }
                }
            }

            $balance_amount = 0;

            //余额
            if(isset($arg_array['balance']) && !empty($arg_array['balance'])){
                $bill_pay_return = new entity('bill_return_pay');
                $bill_pay_return->return_no = $bill_return_master->return_no;
                $bill_pay_return ->creator = $arg_array['operator'];
                $bill_pay_return -> payTypeID = $arg_array['balance'][0];
                $bill_pay_return -> payTypeName = $arg_array['balance_name'][0];
                $bill_pay_return -> return_pay = $arg_array['balance_amount'][0];
                $this->dbca->save($bill_pay_return);

                $balance_amount += $arg_array['balance_amount'][0];
            }

            $points_amount = 0;

            //积分
            if(isset($arg_array['points']) && !empty($arg_array['points'])){
                $bill_pay_return = new entity('bill_return_pay');
                $bill_pay_return->return_no = $bill_return_master->return_no;
                $bill_pay_return ->creator = $arg_array['operator'];
                $bill_pay_return -> payTypeID = $arg_array['points'][0];
                $bill_pay_return -> payTypeName = $arg_array['points_name'][0];
                $bill_pay_return -> return_pay = $arg_array['points_amount'][0];
                $this->dbca->save($bill_pay_return);

                $points_amount += $arg_array['points_amount'][0];
            }

            $coupon_amount = 0;

            //优惠券、红包
            if(isset($arg_array['coupon_code']) && !empty($arg_array['coupon_code'])){
                foreach($arg_array['coupon_code'] as $coupon){
                    $bill_code_return = new entity('bill_return_coupon_card');
                    $bill_code_return->return_no = $bill_return_master->return_no;
                    $bill_code_return->bill_no = $arg_array['bill_no'];
                    $bill_code_return ->creator = $arg_array['operator'];
                    $bill_code_return -> coupon_code = $coupon;
                    $bill_code_return -> coupon_name = isset($arg_array['coupon_name'][$coupon][0]) ? $arg_array['coupon_name'][$coupon][0] : "";
                    $bill_code_return -> coupon_money = isset($arg_array['coupon_amount'][$coupon][0]) ? $arg_array['coupon_amount'][$coupon][0] : "";
                    $this->dbca->save($bill_code_return);

                    $coupon_amount += isset($arg_array['coupon_amount'][$coupon][0]) ? $arg_array['coupon_amount'][$coupon][0] : 0;
                }
            }

            $card_amount = 0;

            //现金卡
            if(isset($arg_array['card_no']) && !empty($arg_array['card_no'])){
                foreach($arg_array['card_no'] as $card){
                    $bill_code_return = new entity('bill_return_coupon_card');
                    $bill_code_return->return_no = $bill_return_master->return_no;
                    $bill_code_return->bill_no = $arg_array['bill_no'];
                    $bill_code_return ->creator = $arg_array['operator'];
                    $bill_code_return -> card_no = $card;
                    $bill_code_return -> card_name = isset($arg_array['card_name'][$card][0]) ? $arg_array['card_name'][$card][0] : "";
                    $bill_code_return -> card_money = isset($arg_array['card_amount'][$card][0]) ? $arg_array['card_amount'][$card][0] : "";
                    $this->dbca->save($bill_code_return);

                    $card_amount += isset($arg_array['card_amount'][$card][0]) ? $arg_array['card_amount'][$card][0] : 0;
                }
            }


            if($bill_master->bill_status != 7){//未完成

                if($bill_master->pay_type == 1){//主支付方式类型：1、货到付款 2、在线支付

                    //实际应收金额 = 订单应收金额 + 已收金额 + 去零金额，不含运费，不含附加费
                    $real_receivable_money = $bill_master->bill_receivable_money + $bill_master->bill_received_money + $bill_master->bill_unreceived_money;

                    //使用余额、积分、优惠券、现金卡支付的金额
                    $other_price = $balance_amount + $points_amount/100 + $coupon_amount + $card_amount;

                    //实际应收金额 -= 本次退货金额
                    $real_receivable_money -= $return_pay;

                    //退货后的订单应收金额，取整（不四舍五入）
                    $bill_receivable_money = floor($real_receivable_money);

                    //订单应收金额
                    $bill_master->bill_receivable_money = $bill_receivable_money;

                    //订单去零金额，全退：去零金额为0，部分退：重新计算去零金额
                    if($bill_receivable_money == 0){
                        $bill_master->bill_unreceived_money = 0;
                    }else{
                        //退货后的订单去零金额
                        //$bill_unreceived_money = round($bill_totalPaid - $bill_receivable_money,2,PHP_ROUND_HALF_DOWN);
                        $bill_unreceived_money = $real_receivable_money - $bill_receivable_money;
                        $bill_master->bill_unreceived_money = $bill_unreceived_money;
                    }

                    //订单已收金额
                    $bill_master->bill_received_money -= $other_price;

                }
            }

            $this->dbca->save($bill_master);

            //保存退货商品
            foreach($bill_return_goods_array as &$bill_return_goods_obj) {
                $bill_return_goods_obj->return_no = $bill_return_master->return_no;
                $this->dbca->save($bill_return_goods_obj);
            }

            $bill_alter_array[] = '退货单编号：' . $bill_return_master->return_no;

            $log_arg_array['logItem'] = $bill_no;
            $log_arg_array['logCategoryID'] = 1;
            $log_arg_array['operator'] = $arg_array['operator'];
            $log_arg_array['extend_1'] = implode('<br>', $bill_alter_array);
            $log_arg_array['extend_2'] = implode('<br>', $bill_goods_alter_array);
            $log_arg_array['extend_5'] = $bill_master->bill_status;

            //保存订单日志
            $logHandler->saveLogInfo( $log_arg_array );


            //===================保存订单修改提示(退货)start=========================

            //订单修改对生产部、配送部的通知 保存到 bill_alter_notice

            //查询商品信息
            $arg_array = array(
                'bill_no' => $bill_no
            );

            //加载类文件
            quanli_include('module/base/bill/billSearch.class.php');
            //实例订单查询类
            $billSearch = new billSearch();
            $bill_goods_array = $billSearch->searchBillGoods($arg_array);
            $goods_array = array();

            foreach($bill_goods_array as $goods){

                if ($goods_array[$goods['goods_postID']]) {
                    $goods_array[$goods['goods_postID']][2] += $goods['goods_amount'];
                } else {
                    $goods_array[$goods['goods_postID']] = array(
                        $goods['goods_name'],
                        $goods['goods_spec'],
                        $goods['goods_amount']
                    );
                }
            }

            $goodsStr = "";

            foreach($goods_array as $data){
                $goodsStr .= $data[0];
                $goodsStr .= ",";
                $goodsStr .= $data[1];
                $goodsStr .= ",";
                $goodsStr .= $data[2] ."个";
                $goodsStr .= ";";
            }

            //实例化订单修改提示表
            $bill_alter_notice = new entity('bill_alter_notice');
            $bill_alter_notice->creator = $arg_array['operator'];
            $bill_alter_notice->createTime = $this->sys_datetime;
            $bill_alter_notice->bill_no = $bill_no;
            $bill_alter_notice->bill_code = $bill_master->bill_code;
            $bill_alter_notice->goods_info = $goodsStr;
            $bill_alter_notice->bill_status = $bill_master->bill_status;
            $bill_alter_notice->city_id = $bill_master->deliver_cityid;
            $bill_alter_notice->distribution_id = $bill_master->distribution_id;
            $bill_alter_notice->distribution_name = $bill_master->distribution_name;
            $bill_alter_notice->alter_content = '订单已退货';
            $bill_alter_notice->send_date = $bill_master->send_date;
            $bill_alter_notice->is_handle = 2;//默认未处理
            $this->dbca->save( $bill_alter_notice );


            //===================保存订单修改提示(退货)end=========================


            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
            //退货单日志参数
            $log_return_array = array(
                'logCategoryID' => 15,//回款日志编号
                'logItem' => $bill_return_master->return_no,//退款单号
                'extend_1' => '创建退货单',//操作名称（退款单建立OR修改）
                'extend_5' => $bill_return_master->return_status,//退款单状态
                'operator' => $bill_return_master->creator ,//创建人
                'extend_2'=>'', //具体操作内容
            );
            $logHandler->saveLogInfo($log_return_array);
            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();
            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => 'ok' );

    }

    /**
     * 审核退换货单
     * @param $arg_array
     * @return array
     */
    public function audit( $arg_array ) {

        global $G_PGLOB;

        //加载类文件
        quanli_require('module/base/bill/billSearch.class.php');

        try {

            //查询退换货单信息
            $return_obj = new entity('bill_return');
            $return_obj->return_no = $arg_array['return_no'];
            if (!$this->dbca->fetch($return_obj))
                throw new Exception('退货单信息没有找到', 404);
            if ($return_obj->return_status == 2)
                throw new Exception('退货单已审核', 404);
            if ($return_obj->return_status == 4)
                throw new Exception('退货单已取消', 404);
            $return_obj->return_status = 2;
            $return_obj->confirm_time = $arg_array['datetime'];
            $return_obj->confirmor = $arg_array['operator'];

            $return_sql = "SELECT * FROM bill_return_coupon_card WHERE return_no = ".$arg_array['return_no'];
            $return_array = $this->dbca->stmt_query($return_sql);

            if(!empty($return_array)){

                //实例化优惠券类
                $ebsigCoupon = new quanliCoupon();
                //实例化代金卡类
                $quanliCard = new quanliCard();
                foreach($return_array as $data){
                    if(!empty($data->coupon_code)){

                        $result = $ebsigCoupon->rollbackCoupon($data->coupon_code , $data->bill_no);

                        if($result['code'] != 200){
                            return array( 'code' => $result['code'], 'message' => $result['message'] );
                        }
                    }
                    if(!empty($data->card_no)){
                        $return = $quanliCard->rollbackCard($data->card_no , $data->bill_no, 1);

                        if($return['code'] != 200){
                            return array( 'code' => $result['code'], 'message' => $result['message'] );
                        }
                    }

                }
            }

            $return_sql = "SELECT * FROM bill_return_pay WHERE return_no = ".$arg_array['return_no'];
            $return_array = $this->dbca->stmt_query($return_sql);

            if($return_array){
                //实例化ebsig接口操作类
                $ebsigEai = eai_crm();

                foreach($return_array as $pay_type){

                    //余额
                    if($pay_type->payTypeID == G_CASH_ID){
                        $arg_array = array(
                            'operator' => $G_PGLOB->currentUserID,
                            'pcustID' =>$return_obj->pcustID,
                            'subjectId' => $pay_type->payTypeID,
                            'amount' => $pay_type->return_pay,
                            'remark' => "订单号：" . $return_obj->bill_no . " 退货，账户余额回滚"
                        );
                        $result_array = $ebsigEai->recharge($arg_array);

                        if($result_array['code'] != 200){
                            returnJsonData($result_array['message'], $result_array['code']);
                        }
                    }

                    //积分
                    if($pay_type->payTypeID == G_POINTS_ID){
                        $arg_array = array(
                            'operator' => $G_PGLOB->currentUserID,
                            'pcustID' =>$return_obj->pcustID,
                            'subjectId' => $pay_type->payTypeID,
                            'amount' => $pay_type->return_pay,
                            'remark' => "订单号：" . $return_obj->bill_no . " 退货，账户积分回滚"
                        );
                        $result_array = $ebsigEai->recharge($arg_array);

                        if($result_array['code'] != 200){
                            returnJsonData($result_array['message'], $result_array['code']);
                        }
                    }
                }
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
            quanli_require('module/base/customer/logHandler.class.php');
            //日志类
            $logHandler = new logHandler( $this->dbca );

            //退货单日志参数
            $log_array = array(
                'logCategoryID' => 15,//退货日志编号
                'logItem' => $return_obj->return_no,//退货单号
                'extend_1' => '申核退货单',//操作名称（退款单建立OR修改）
                'extend_5' => $return_obj->return_status,//退款单状态
                'operator' => $arg_array['operator'] ,//创建人
                'extend_2'=>'', //具体操作内容
            );

            $logHandler->saveLogInfo($log_array);
            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

            //更新退货单
            $this->dbca->save( $return_obj );

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '退货单审核成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }

        }

    }

    /**
     * 取消退换货单
     * @param $arg_array
     * @return array
     */
    public function cancel( $arg_array ) {

        //加载类文件
        quanli_include('module/base/customer/logHandler.class.php');

        //实例日志类
        $logHandler = new logHandler( $this->dbca );

        try {

            //查询退换货单信息
            $return_obj = new entity('bill_return');
            $return_obj->return_no = $arg_array['return_no'];
            if (!$this->dbca->fetch($return_obj)) {
                throw new Exception('退货单信息没有找到', 404);
            }
            if ($return_obj->return_status == 2) {
                throw new Exception('退货单已审核', 404);
            }
            if ($return_obj->return_status == 4) {
                throw new Exception('退货单已取消', 404);
            }
            $return_obj->return_status = 4;
            $return_obj->cancel_time = $arg_array['datetime'];
            $return_obj->cancel_operator = $arg_array['operator'];


            //修改订单退货数量
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $return_obj->bill_no;
            if (!$this->dbca->fetch($bill_obj)) {
                throw new Exception('订单信息没有找到', 404);
            }
            $bill_obj->bill_withdrawAmount -= $return_obj->return_amount;
            if ($bill_obj->bill_withdrawAmount < 0) {
                $bill_obj->bill_withdrawAmount = 0;
            }
            $bill_alter_array[] = '取消退货数量：' . $return_obj->return_amount;
            $bill_alter_array[] = '  服务单编号：' . $return_obj->return_code;

            //修改订单商品退货数量
            $search_args_array = array(
                'return_no' => $return_obj->return_no
            );
            $return_goods_array = $this->searchBillReturnGoods( $search_args_array );
            if (!$return_goods_array) {
                throw new Exception('退货商品信息没有找到', 404);
            }
            foreach($return_goods_array as &$return_goods) {

                $bill_goods_obj = new entity('bill_goods');
                $bill_goods_obj->bill_no = $return_obj->bill_no;
                $bill_goods_obj->bill_goods_no = $return_goods['bill_goods_no'];
                if (!$this->dbca->fetch($bill_goods_obj)) {
                    throw new Exception('订单商品信息没有找到', 404);
                }
                $bill_goods_obj->goods_withdrawAmount -= $return_goods['goods_amount'];
                $bill_goods_array[] = $bill_goods_obj;

                //记录订单商品修改日志
                $bill_goods_alter_array[] = '<span class="red">退货取消</span>：';
                $bill_goods_alter_array[] = '　　名称：' . $return_goods['goodsName'];
                $bill_goods_alter_array[] = '　　规格：' . $return_goods['spec'];
                $bill_goods_alter_array[] = '　　数量：' . $return_goods['goods_amount'];

            }


            //订单日志
            $log_arg_array['logItem'] = $return_obj->bill_no;
            $log_arg_array['logCategoryID'] = 1;
            $log_arg_array['operator'] = $arg_array['operator'];
            $log_arg_array['extend_1'] = implode('<br>', $bill_alter_array);
            $log_arg_array['extend_2'] = implode('<br>', $bill_goods_alter_array);
            $log_arg_array['extend_5'] = $bill_obj->bill_status;

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //更新退换货单
            $this->dbca->save( $return_obj );


            //更新订单
            $this->dbca->save($bill_obj);

            //更新订单商品
            foreach($bill_goods_array as &$goods_obj) {
                $this->dbca->save($goods_obj);
            }

            //保存订单日志
            $logHandler->saveLogInfo( $log_arg_array );


            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
            //退货单日志参数
            $log_array = array(
                'logCategoryID' => 15,//退货日志编号
                'logItem' => $return_obj->return_no,//退货单号
                'extend_1' => '取消退货单',//操作名称（退款单建立OR修改）
                'extend_5' => $return_obj->return_status,//退款单状态
                'operator' => $arg_array['operator'] ,//创建人
                'extend_2'=>'', //具体操作内容
            );

            $logHandler->saveLogInfo($log_array);
            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '退货单取消成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }

        }

    }


    /**
     * 退货收货
     * @param $arg_array
     * @return array
     */
    public function  receiving( $arg_array ) {
    	//add by yim.hu 20141201 35-FUN-BK-0035 订单状态优化 --start
    	//增加一个全局变量
    	global $G_PGLOB;
    	//add by yim.hu 20141201 35-FUN-BK-0035 订单状态优化 --end
        //加载类文件
        quanli_include('module/base/customer/logHandler.class.php');

        //实例日志类
        $logHandler = new logHandler( $this->dbca );

        try {

            //查询退换货单信息
            $return_obj = new entity('bill_return');
            $return_obj->return_no = $arg_array['return_no'];
            if (!$this->dbca->fetch($return_obj)) {
                throw new Exception('退货单信息没有找到', 404);
            }
            if ($return_obj->return_status == 4) {
                throw new Exception('退货单已取消', 404);
            }
            $return_obj->return_status = 3;
            $return_obj->delivery_time = $arg_array['datetime'];
            $return_obj->delivery_operator = $arg_array['operator'];

            //订单日志
            $log_arg_array['logItem'] = $return_obj->bill_no;
            $log_arg_array['logCategoryID'] = 1;
            $log_arg_array['operator'] = $arg_array['operator'];
            $log_arg_array['extend_1'] = "确认收货";
            //add by yim.hu 20141201 FUN-BK-0035 订单状态优化 --start
            //增加一个订单状态功能
            //通过订单号来查询当前订单的状态
            $sql = "select bill_status from bill_master where bill_no = ".$return_obj->bill_no;
            $reuslt = $G_PGLOB->DBCA->stmt_query($sql);
            $log_arg_array['extend_5'] = $reuslt[0]->bill_status;
            //add by yim.hu 20141201 FUN-BK-0035 订单状态优化 --end

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //更新退货单
            $this->dbca->save( $return_obj );

            //保存订单日志
            $logHandler->saveLogInfo( $log_arg_array );

            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
            //退货单日志参数
            $log_return_array = array(
                'logCategoryID' => 15,//退货日志编号
                'logItem' => $return_obj->return_no,//退货单号
                'extend_1' => '收货',//操作名称（退款单建立OR修改）
                'extend_5' => $return_obj->return_status,//退款单状态
                'operator' => $arg_array['operator'] ,//创建人
                'extend_2'=>'', //具体操作内容
            );

            $logHandler->saveLogInfo($log_return_array);
            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '保存成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }

        }

    }

    /**
     * 取得订单退货状况  部分退/全退
     * @param $bill_code
     * @return string
     * add by allen.qiang 20141022
     */
    public function GetReturnKind( $bill_code ) {

        $return_sql="SELECT bm.`bill_totalAmount` AS bm_cnt,IFNULL((SELECT SUM(return_amount)  FROM bill_return WHERE bill_code = bm.`bill_code`
                    AND return_status <> 4),0) AS br_cnt FROM  bill_master bm WHERE bm.bill_code = ?";
        $return_array = $this->dbca->stmt_query($return_sql,'s',$bill_code);
        if(!$return_array)//无数据
            return '';
        if($return_array[0]->br_cnt==0)//无退货数据
            return '';

        if($return_array[0]->bm_cnt!=$return_array[0]->br_cnt)
            return '部分退货';

        if($return_array[0]->bm_cnt==$return_array[0]->br_cnt)
            return '全退';

        //其他情况
        return '';
    }


    /**
     * 配送自购
     * @param $arg_array
     * @return array
     * add by allen.qiang 20141110 FUN-BK-0022-配送部自购业务需求
     */
    public function  purchaseBillReturn( $arg_array ) {

        //加载类文件
        quanli_include('module/base/customer/logHandler.class.php');

        //实例日志类
        $logHandler = new logHandler( $this->dbca );

        try {

            //查询退换货单信息
            $return_obj = new entity('bill_return');
            $return_obj->return_no = $arg_array['return_no'];
            if (!$this->dbca->fetch($return_obj)) {
                throw new Exception('退货单信息没有找到', 404);
            }
            if ($return_obj->return_status == 4) {
                throw new Exception('退货单已取消', 404);
            }
            $return_obj->return_type = $arg_array["return_type"];
            $return_obj->return_status = $arg_array["return_status"];
            $return_obj->purchase_price = $arg_array["purchase_price"];
            $return_obj->purchase_time = $arg_array['datetime'];
            $return_obj->purchase_operator = $arg_array['operator'];

            //添加订单日志
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $return_obj->bill_no;
            if (!$this->dbca->fetch($bill_obj)) {
                throw new Exception('订单信息没有找到', 404);
            }
            $search_args_array = array(
                'return_no' => $return_obj->return_no
            );
            $return_goods_array = $this->searchBillReturnGoods( $search_args_array );
            if (!$return_goods_array) {
                throw new Exception('退货商品信息没有找到', 404);
            }
            $bill_goods_alter_array[] = '<span class="red">配送自购：</span>';
            foreach($return_goods_array as &$return_goods) {
                //记录订单商品修改日志
                $bill_goods_alter_array[] = '　　自购商品：' . $return_goods['goodsName'].'，'.'规格：' . $return_goods['spec'].'，'.'数量：' . $return_goods['goods_amount'];
            }
            $bill_goods_alter_array[] = '　　配送自购金额：' . $arg_array['purchase_price'];

            //订单日志
            $log_arg_array['logItem'] = $return_obj->bill_no;
            $log_arg_array['logCategoryID'] = 1;
            $log_arg_array['operator'] = $arg_array['operator'];
            $log_arg_array['extend_1'] = "配送自购";
            $log_arg_array['extend_2'] = implode('<br>', $bill_goods_alter_array);
            $log_arg_array['extend_5'] = $bill_obj->bill_status;

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //更新退货单
            $this->dbca->save( $return_obj );

            //保存订单日志
            $logHandler->saveLogInfo( $log_arg_array );

            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- start
            //退货单日志参数
            $log_array = array(
                'logCategoryID' => 15,//退货日志编号
                'logItem' => $return_obj->return_no,//退货单号
                'extend_1' => '配送自购',//操作名称（退款单建立OR修改）
                'extend_5' => $return_obj->return_status,//退款单状态
                'operator' => $arg_array['operator'] ,//创建人
                'extend_2'=>'', //具体操作内容
            );

            $logHandler->saveLogInfo($log_array);
            //add by sun.qiang  2015-03-25 MK-FUN-BK-004 新增品控意见 --- end

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '保存成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }
        }
    }
}